package com.lwc.cfdns.pojo.bo;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.Data;

import javax.validation.constraints.Max;

/**
 * 分页参数
 *
 * @author luwc
 * @title PageDTO
 * @description
 * @time 2023/4/26 09:00:25
 * @version: 1.0
 */
@Data
public abstract class AbstractPageQuery<T> {
    private static final int MAX_PAGE_NUM = 200;
    private static final int MAX_PAGE_SIZE = 5000;
    private static final String ASC = "ascending";
    private static final String DESC = "descending";

    // 当前页
    @Max(MAX_PAGE_NUM)
    protected Integer pageNum = 1;

    // 默认页条数
    @Max(MAX_PAGE_SIZE)
    protected Integer pageSize = 10;

    protected String orderByColumn;

    protected String isAsc;

    /**
     * 分页
     *
     * @param
     * @return Page<Model>
     * @throws
     * @version 1.0.0
     * @author luwc
     * @time 2023/4/26 15:01:10
     */
    public Page<T> toPage() {
        return new Page<T>(pageNum, pageSize);
    }

    /**
     * 生成query conditions
     *
     * @param
     * @return LambdaQueryWrapper<T>
     * @throws
     * @version 1.0.0
     * @author luwc
     * @time 2023/4/26 20:17:17
     */
    public abstract LambdaQueryWrapper<T> toQueryWrapper();

    public void addSortCondition(QueryWrapper<T> queryWrapper) {
        if (queryWrapper != null) {
            boolean sortDirection = convertSortDirection();
            queryWrapper.orderBy(StringUtils.isNotBlank(orderByColumn), sortDirection,
                    StringUtils.underlineToCamel(orderByColumn));
        }
    }

    private boolean convertSortDirection() {
        boolean orderDirection = true;
        if (StringUtils.isNotEmpty(isAsc)) {
            if (ASC.equals(isAsc)) {
                orderDirection = true;
            } else if (DESC.equals(isAsc)) {
                orderDirection = false;
            }
        }
        return orderDirection;
    }
}